import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:flutter/cupertino.dart';
import 'package:gim_plugin_example/config.dart';
import 'package:gim_plugin_example/utils/logger_utils.dart';
import 'package:gim_plugin_example/utils/permission_utils.dart';
import 'package:gim_plugin_example/utils/toast_utils.dart';
import 'package:agora_rtc_engine/rtc_local_view.dart' as RtcLocalView;
import 'package:agora_rtc_engine/rtc_remote_view.dart' as RtcRemoteView;

class ArtcSdk {
  RtcEngine? client;

  bool _isAlert = false;

  DateTime _dt = DateTime.now().subtract(const Duration(hours: 1));

  Future<bool> initClient(BuildContext context, {bool videoCall = true, required RtcEngineEventHandler cb}) async {
    if (!(await applyCameraPermission(context: context))) {
      return false;
    }
    if (!(await applyMicrophonePermission(context: context))) {
      return false;
    }
    cb.lastmileQuality = (NetworkQuality quality) {
      //监听本地网络状态
      if (quality.index >= 4 && quality.index <= 6) {
        DateTime now = DateTime.now();
        if (now.difference(_dt).inSeconds >= 6) {
          _dt = now;
          showToast('您当前网络质量不佳');
        }
      }
    };
    cb.networkQuality = (int uid, NetworkQuality txQuality, NetworkQuality rxQuality) {
      //先确认一下自己的上行网络有没有问题
      DateTime now = DateTime.now();
      if (uid == 0 && txQuality.index >= 4 && txQuality.index <= 6 && rxQuality.index >= 4 && rxQuality.index <= 6) {
        //走到这里说明自己的上行网络《有问题》
        _isAlert = true;
        if (now.difference(_dt).inSeconds >= 6) {
          _dt = now;
          showToast('当前通话您的网络不佳');
        }
        //自己的上行网络没问题，再判断对方的上行网络有没有问题
      } else if (uid != 0 &&
          txQuality.index >= 4 &&
          txQuality.index <= 6 &&
          rxQuality.index >= 4 &&
          rxQuality.index <= 6) {
        //走到这里说明对方的上行网络《有问题》
        if (!_isAlert) {
          if (now.difference(_dt).inSeconds >= 6) {
            _dt = now;
            showToast('当前通话对方网络不佳');
          }
        }
        _isAlert = false;
      }
    };
    client = await RtcEngine.createWithContext(RtcEngineContext(artcAppID));
    client!.setEventHandler(cb);
    if (videoCall) {
      await client!.enableVideo();
      await client!.enableLocalVideo(true);
    } else {
      await client!.disableVideo();
      await client!.enableLocalVideo(false);
    }
    await client!.enableAudio();
    await client!.enableLocalAudio(true);
    await client!.setChannelProfile(ChannelProfile.LiveBroadcasting);
    await client!.setClientRole(ClientRole.Broadcaster);
    return true;
  }

  Future<void> createChannel({required int uid, required String rtcToken, required String channelId}) async {
    loggerDebug("rtcToken=> $rtcToken\nchannelId=> $channelId\nuid=> $uid");
    await client!.joinChannel(rtcToken, channelId, null, uid);
    await client!.startPreview();
  }

  Future<void> delChannel() async {
    if (client == null) return;
    await client?.leaveChannel();
    await client?.destroy();
    client = null;
  }

  renderRemoteVideo({required int uid, required String channelId}) =>
      RtcRemoteView.SurfaceView(uid: uid, channelId: channelId);

  renderLocalPreview({required String channelId}) => RtcLocalView.SurfaceView(channelId: channelId);
}
